<template>
  <!--回款报表-->
  <section class="page repayment-report">
    <data-form :submitLoading="submitLoading" :model="searchModel" @onSearch="refreshData" @handleResetForm="handleResetForm">
      <template slot="inputs">
        <el-form-item label="机构" prop="deptId">
          <!-- <el-cascader v-model="departmentIds" :options="deptTreeData" :props="{value:'id',label:'deptName'}" change-on-select :show-all-levels="false" clearable></el-cascader> -->
          <select-department :specialOptions="specialOptions" v-model="searchModel.deptId" @on-select-change="(id, code) => departemntChange(id, code)"></select-department>
        </el-form-item>
        <el-form-item label="催收员" prop="collectorId">
          <el-select placeholder="请选择" v-model="searchModel.collectorId" clearable>
            <el-option v-for="{id,realName} in userSet" :key="id" :label="realName" :value="id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="还款时间" prop="paymentTime">
          <el-date-picker type="daterange" :editable="false" v-model="searchModel.paymentTime" placeholder="选择日期时间" clearable></el-date-picker>
        </el-form-item>
      </template>
    </data-form>
    <data-box :data="dataSet" rowSpanKey="deptId" :rowClassName="rowClassName" hiddenIndex>
      <template slot="buttons">
        <el-button @click="exportCaseInfo" v-auth="2009">导出</el-button>
      </template>
      <template slot="columns">
        <el-table-column label="考察对象">
          <el-table-column label="机构" prop="deptId" :formatter="row => row.deptName"></el-table-column>
          <el-table-column label="姓名" prop="collectorRealName"></el-table-column>
        </el-table-column>
        <el-table-column label="统计数据">
          <!-- <el-table-column label="还款时间" prop="entryTime" :formatter="row => $filter.dateFormat(row.entryTime)"></el-table-column> -->
          <el-table-column label="回款金额(单位:元)" prop="repayAmount" :formatter="row => $filter.toThousands(row.repayAmount)"></el-table-column>
        </el-table-column>
      </template>
    </data-box>

  </section>
</template>

<script lang="ts">
import Vue from 'vue';
import Component from 'vue-class-component';
import { Auth, Layout, Dependencies } from '~/core/decorator';
import DataBox from '~/components/common/data-box.vue';
import DataForm from "~/components/common/data-form.vue"
import { ReportManageService } from "~/services/domain-service/report-manage.service";
import { UserService } from "~/services/management-service/user.service";
import SelectDepartment from "~/components/business-component/select-department.vue";
import { CommonService } from "~/utils/common.service";
import { DepartmentService } from "~/services/management-service/department.service";

// @Auth(1004)
@Layout('workspace')
@Component({
  components: {
    DataBox,
    DataForm,
    SelectDepartment
  }
})
export default class RepaymentReport extends Vue {
  @Dependencies(ReportManageService) private reportManageService: ReportManageService;
  @Dependencies(UserService) private userService: UserService;
  @Dependencies(DepartmentService) private departmentService: DepartmentService;
  private groupKey = "deptId"
  private searchModel: any = {
    deptId: "",
    collectorId: "",
    deptCode: "",
    paymentTime: ''
  }
  private dataSet: any[] = [];
  private userSet: any[] = []
  private specialOptions: any[] = []
  private submitLoading: any = true

  private refreshData() {
    const params: any = {
      deptId: this.searchModel.deptId,
      collectorId: this.searchModel.collectorId,
      deptCode: this.searchModel.deptCode,
      repaymentTimeStart: this.$filter.dateRanageFormat(this.searchModel.paymentTime).start,
      repaymentTimeEnd: this.$filter.dateRanageFormat(this.searchModel.paymentTime).end
    }
    this.reportManageService.getAllRepaymentReportData(params)
      .subscribe(data => {
        this.dataSet = data
        this.submitLoading = false
        this.groupData()
        // 因为统计数据插入了新数据，所以需要排序一次
        this.dataSet.sort((a, b) => a.deptId - b.deptId)
      })
  }

  /**
   * 统计数据
   */
  private groupData() {
    // 1.统计关联键的值
    const values = this.dataSet.map(v => v[this.groupKey])

    const set = new Set<string>(values)
    set.forEach(id => {
      const filterRows = this.dataSet.filter(x => x[this.groupKey] === id)
      const repayAmount = filterRows.reduce((s, c) => s + c.repayAmount, 0)
      const totalValue = {
        deptId: id,
        collectorRealName: `合计：${filterRows.length}`,
        repayAmount,
        totalFlag: true
      }
      this.dataSet.push(totalValue)
    })
  }

  //案件导出
  private exportCaseInfo() {
    if(this.dataSet.length === 0){
      this.$message("暂无数据可以导出")
      return
    }
    const params: any = {
      deptId: this.searchModel.deptId,
      collectorId: this.searchModel.collectorId,
      deptCode: this.searchModel.deptCode,
      repaymentTimeStart: this.$filter.dateRanageFormat(this.searchModel.paymentTime).start,
      repaymentTimeEnd: this.$filter.dateRanageFormat(this.searchModel.paymentTime).end
    }
    this.reportManageService
      .exportAllRepaymentReportData(params)
      .subscribe(data => this.$common.downloadFile(data.url));
  }

  private rowClassName({ row }) {
    if (row.totalFlag) return 'total'
  }

  private departemntChange(id,code) {
    this.searchModel.deptCode = code
    this.searchModel.collectorId = ''
    if (!code) {
      this.userSet = []
    } else {
      this.getAllUserByDeptCode(code)
    }
  }

  private getAllUserByDeptCode(deptCode: string) {
    this.userService.getAllUsersList({deptCode}).subscribe(
      data => this.userSet = data
    )
  }
  //获取委外和电催部门数据
  private queryTelAndVisitDepartment() {
    this.departmentService.queryTelAndVisitDepartment().subscribe(
      data =>{ this.specialOptions = CommonService.generateTreeData(data, {
        keyName: 'id',
        parentKeyName: 'parentId'
      })
    })
  }

  private handleResetForm() {
    this.searchModel.deptCode = ''
  }
  private mounted() {
    this.refreshData()
    this.queryTelAndVisitDepartment()
  }

}
</script>

<style lang="less">
.page.repayment-report {
  .data-box {
    .el-table__row {
      &.total {
        font-weight: bold;
        font-size: 16px;
      }
    }
  }
}
</style>
